package router

import (
	"gostore/config"
	_ "gostore/docs"
	"gostore/router/middleware"
	"gostore/util"
	"gostore/util/log"
	"strings"

	"github.com/gin-gonic/gin"
	swaggerFiles "github.com/swaggo/files"
	ginSwagger "github.com/swaggo/gin-swagger"
)

const (
	MGet  int = 0
	MPost int = 1
	MPut  int = 2
	MDel  int = 3
)

type Route struct {
	Method  int
	Path    string
	Handler gin.HandlerFunc
}

var r *gin.Engine

func GetRouter() *gin.Engine {
	if r == nil {
		r = gin.Default()
	}
	// gin.SetMode(gin.ReleaseMode)
	return r
}

func AddRouteGroup(prefix string, routes []Route) {
	s1 := strings.Split(prefix, "/")
	for _, v := range routes {
		s4 := ""
		s2 := util.Join(s1, "/")
		if len(v.Path) > 0 {
			s2 += "/"
			s3 := strings.Split(v.Path, "/")
			s4 = util.Join(s3, "/")
		}
		// log.Info("s2+s4", s2, s4)
		AddRoute(v.Method, s2+s4, v.Handler)
	}
}

func AddRoute(method int, path string, handler gin.HandlerFunc) {
	switch method {
	case MPost:
		r.POST(path, handler)
	case MPut:
		r.PUT(path, handler)
	case MDel:
		r.DELETE(path, handler)
	default:
		r.GET(path, handler)
	}
}

type ModelRoute interface {
	AddNewRoutes()
}

func LoadRouters(list ...interface{}) *gin.Engine {
	l := log.Factory(LoadRouters)
	l.Info("loading routers")

	r := GetRouter()
	r.GET("/swagger/*any", ginSwagger.WrapHandler(swaggerFiles.Handler))
	r.Use(Cors())

	authApi := r.Group("/api/auth/")
	{
		authApi.POST("login", middleware.Login)
	}
	captcha := r.Group("/api/captcha")
	{
		captcha.GET("", middleware.GetCaptcha)
		captcha.POST("verify", middleware.CaptchaVerify)
	}

	// @Todo
	// 带测试token的用户
	if !config.Cfg.Server.Debug {
		r.Use(middleware.JWT())
	}

	// r.Use(middleware.Auth())

	for i := 0; i < len(list); i++ {
		if target, ok := list[i].(ModelRoute); ok {
			target.AddNewRoutes()
		}
	}

	return r
}

//跨域
func Cors() gin.HandlerFunc {
	return func(c *gin.Context) {
		c.Header("Access-Control-Allow-Origin", "*")
		c.Next()
	}
}
